<!--
 * @页面名称:全文页面
 * @描述: 
 * @作者: 
 * @Date:
-->
<template>
  <div style="height: calc(100% - 55px)">
    <div class="header-button-ri" style="margin-bottom: 10px" v-if="!userStore.userInfo.U_ReadOnly">
      <slot name="toolButton">
        <el-tooltip
          class="box-item"
          effect="dark"
          :content="item.title"
          placement="top"
          v-for="(item, index) in buttonPermission"
          :key="index"
        >
          <el-button :icon="item.icon" :disabled="toggleDisabled(item)" circle @click="onClickVerb(item.alias)" />
        </el-tooltip>
      </slot>
    </div>
    <div style="height: calc(100% - 12px)">
      <stable
        ref="vxeTable"
        :columns="tableSetting.columns"
        :tableMenu="tableSetting.tableMenu"
        :loading="tableSetting.loading"
        @rowClick="rowClick"
        @rowdblClick="rowdblClick"
        @selectionChange="selectChange"
        @menuClick="menuClick"
      ></stable>
    </div>
    <!-- 全文预览 -->
    <preview
      v-if="fulltextConfig.visible"
      :visible="fulltextConfig.visible"
      :type="fulltextConfig.type"
      :fileList="fulltextConfig.fileList"
      :download="fulltextConfig.download"
      :print="fulltextConfig.print"
      @updataVisible="updataVisible"
    ></preview>
    <!-- 上传文件 -->
    <input ref="uploadFile" multiple type="file" @change="uploadFileChange" style="display: none" />
    <!-- 文件上传进度条 -->
    <el-dialog
      title="正在上传文件...请稍等"
      v-model="fulltextModal.isShow"
      width="30%"
      class="progress-modal"
      top="300px"
      center
      :close-on-click-modal="false"
      :showClose="false"
    >
      <template #footer>
        <span class="dialog-footer">
          <el-progress :text-inside="true" :stroke-width="20" :percentage="fulltextModal.percent" status="success" />
        </span>
      </template>
    </el-dialog>
    <!-- 权限管理 -->
    <AuthorityManage :config="AuthConfig" :data="fatherObj" :fulltextData="tableSetting.selectData"></AuthorityManage>
    <!-- SingalrModal弹框 -->
    <SingalrModal
      v-model:visible="singalrModal.visible"
      :discontinueFont="singalrModal.discontinueFont"
      @cease="cease"
      @cancel="cancel"
      width="50vw"
    >
      <div style="margin-bottom: 20px; text-align: center">
        <el-text type="primary">"{{ singalrModal.text }}"</el-text>
      </div>
      <el-progress :text-inside="true" :stroke-width="20" :percentage="singalrModal.percent" status="success" />
    </SingalrModal>
  </div>
</template>

<script setup lang="tsx">
import { reactive, ref, markRaw, watch, computed, onMounted } from "vue";
import { EyeOutlined, EyeTwoTone } from "@ant-design/icons-vue";
import { fileSizeFormat } from "@/utils/formatter";
import { previewFulltext } from "@/components/Preview/ts/index";
import Preview from "@/components/Preview/Preview.vue";
import { useDynamicStore } from "@/stores/modules/dynamic";
import { useUserStore } from "@/stores/modules/user";
import { useAppStore } from "@/stores/modules/app";
import { useDynamicButtonStore } from "@/stores/modules/dynamicButton";
import useCurrentInstance from "@/utils/useCurrentInstance";
import { saveAs } from "file-saver";
import AuthorityManage from "../AuthorityManage/index.vue";
import { getSysConfig } from "@/utils/util";
import dtime from "moment";

const { proxy } = useCurrentInstance();
// pinia
const dynamicButton = useDynamicButtonStore();
const dynamicStore = useDynamicStore();
const userStore = useUserStore();
const appStore = useAppStore();
// 父级保存数据
const fatherObj = ref();
// 单击保存对象
const rowClickObj = ref();
// 获取上传文件组件实例
const uploadFile: any = ref(null);
// 获取表格实例
const vxeTable = ref();
// 获取按钮权限
const buttonPermission = computed(() => {
  return dynamicButton.fulltextButtonList;
});
// 表格配置
const tableSetting = reactive({
  columns: [
    { type: "checkbox", width: 55 },
    { title: "序号", field: "AI_Index", width: 80, sortable: true },
    { title: "文件名", field: "AI_Name", sortable: true },
    { title: "文件类型", field: "AI_Source_Extension", width: 150, sortable: true },
    { title: "文件大小", field: "AI_Source_Size", width: 100, sortable: true, formatter: fileSizeFormat },
    { title: "上传时间", field: "AI_UploadDateTime", width: 150, sortable: true },
    { title: "创建时间", field: "AI_FileDateTime", width: 150, sortable: true },
    {
      title: "OCR状态",
      field: "AI_IsOCR",
      slots: {
        default: ({ row }) => {
          return [<div>{row.AI_IsOCR ? <EyeTwoTone /> : <EyeOutlined />}</div>];
        }
      }
    }
  ],
  // data: [],
  selectData: [], // 多选数据
  rowClickObj: {}, //点击保存行数据
  tableMenu: {
    enabled: true,
    className: "my-menus",
    body: {
      options: [[{ code: "allInfo", name: "加入外连清单", prefixIcon: "DocumentAdd", className: "my-copy-item" }]]
    }
  },
  loading: false // 表格loading事件
});
// 全文预览配置参数
const fulltextConfig = reactive({
  // 预览全文配置参数
  visible: false,
  fileList: [] as any[],
  type: "",
  download: false,
  print: false
});
// 上传文件进度条配置
const fulltextModal = reactive({
  isShow: false,
  percent: 0
});
// 权限管理配置
const AuthConfig = reactive({
  visible: false,
  title: "",
  type: ""
});
// singalr弹框配置
const singalrModal = reactive({
  visible: false, //弹框状态
  discontinueFont: "中止", // 弹框按钮文字
  discontinueStatus: false, // 弹框按钮状态
  networkStatus: true, // 单个网络状态
  AllNetworkStatus: true, // 所有的网络状态
  circulatingIndex: 0, // 循环索引
  percent: 0, // 进度条进度
  text: "" // singal文字
});
// 获取全文数据
const getData = (data: any) => {
  fatherObj.value = data;
  proxy.$vueAxios
    .post("Master_Base_AllInfos/GetConditional", {
      order: "AI_Index asc",
      dtoList: [{ fieldName: "Record_ID", fieldValue: data.Record_ID }]
    })
    .then((res: any) => {
      // tableSetting.data = res.List;
      dynamicStore.setFulltextData(res.List);
    });
};
// 点击事件
const rowClick = ({ row }: any) => {
  // 改变按钮状态
  vxeTable.value.setCheckboxRow([row], true);
  selectChange([row]);
  rowClickObj.value = row;
};
// 双击打开全文
const rowdblClick = ({ row }: any) => {
  previewFulltext(
    {
      id: row.AI_ID,
      fulltextRow: row,
      fulltextTableData: dynamicStore.fulltextData,
      config: fulltextConfig,
      IsAllow: true
    },
    proxy
  );
};
// 多选
const selectChange = (val: any) => {
  tableSetting.selectData = val;
};
// 上传
const upload = () => {
  uploadFile.value.click();
};
// 上传按钮点击事件
const uploadFileChange = async (event: any) => {
  const PieceSize = getSysConfig("PieceSize") ? getSysConfig("PieceSize") : 10;
  // const limitSize = 1024 * 1024 * 30;
  // if (uploadFile.value.files[0].size > limitSize) {
  //   proxy.$message.error("文件大小不能超过30M");
  //   return;
  // }
  const { fulltextData } = dynamicStore;
  const files = uploadFile.value.files;
  const filesLength = files.length;
  fulltextModal.percent = 0;
  let arrList = [...fulltextData];
  const maxIndex =
    fulltextData.length > 0
      ? Math.max.apply(
          Math,
          fulltextData.map(item => {
            return item.AI_Index;
          })
        )
      : 0;
  let fileCount = 0;
  let bytesPerPiece = 1024 * 1024 * PieceSize; // 每个文件切片大小定为10MB
  let totalPieces;
  for (let i = 0; i < files.length; i++) {
    const lastFileTime = dtime(files[i].lastModified).format("YYYY-MM-DD HH:mm:ss");
    let blob = files[i];
    let start = 0;
    let end;
    let progressIndex = 1;
    let filesize = blob.size;
    // 计算文件切片总数
    totalPieces = Math.ceil(filesize / bytesPerPiece);
    const AIID = proxy.$global.createID();
    for (let uploadIndex = 1; uploadIndex <= totalPieces; uploadIndex++) {
      end = Math.min(filesize, start + bytesPerPiece);
      let chunk = blob.slice(start, end); // 切割文件
      const resultObj: any = ref({});
      const fileData: any = new FormData();
      fileData.append("file", chunk);
      fileData.append("AI_ID", AIID);
      fileData.append("PieceTotal", totalPieces as any);
      fileData.append("PieceNow", uploadIndex);
      fileData.append("AI_Name", blob.name);
      fileData.append("AI_FileDateTime", lastFileTime);
      fileData.append("AI_Size", filesize);
      fileData.append("AI_Index", Number(maxIndex) + 1 + i);
      fileData.append("FM_ID", fatherObj.value.FM_ID);
      fileData.append("FMT_ID", fatherObj.value.FMT_ID);
      fileData.append("Record_ID", fatherObj.value.Record_ID);
      resultObj.value["AI_Index"] = Number(maxIndex) + 1 + i;
      resultObj.value["AI_Name"] = blob.name;
      resultObj.value["AI_Source_Size"] = filesize.toString();
      resultObj.value["AI_ID"] = AIID;
      resultObj.value["AI_Source_Extension"] = "." + blob.name.split(".")[1];
      resultObj.value["AI_FileDateTime"] = lastFileTime;
      resultObj.value["AI_UploadDateTime"] = dtime(new Date()).format("YYYY-MM-DD HH:mm:ss");
      fulltextModal.isShow = true;
      const Res = await proxy.$vueAxios.post("MasterBaseAllInfos/Upload/Piece", fileData, { noLoading: true });

      if (!Res.Mark) {
        proxy.$message.warning(`上传错误:${Res.Msg}`);
        fulltextModal.isShow = false;
        break;
      }
      start = start + chunk.size;
      // proxy.$showLoading({ tip: `文件上传中...(${percent}%)` });
      fulltextModal.percent = Math.round((progressIndex / totalPieces / filesLength) * 100);
      progressIndex++;
      // 单个文件传输完成
      if (uploadIndex >= totalPieces) {
        arrList = [...arrList, resultObj.value];
        dynamicStore.setFulltextData(arrList);
        fileCount++;
      }
      // 所有文件传输完成
      if (fileCount >= filesLength) {
        fulltextModal.isShow = false;
      }
    }
  }
  uploadFile.value.value = "";
  // proxy.$hideLoading();
};
// 下载
const download = async () => {
  if (rowClickObj.value) {
    const btey = 1024 * 1024 * 10; // 分片大小为10m
    const totalPieces = Math.ceil(rowClickObj.value.AI_Source_Size / btey);
    let arr: any[] = [];
    for (let i = 0; i < totalPieces; i++) {
      const data = await proxy.$vueAxios.download2(
        "MasterBaseAllInfos/Download",
        {
          AI_ID: rowClickObj.value.AI_ID,
          pieceTotal: totalPieces,
          piece: i + 1
        },
        { noLoading: true }
      );
      const percent = Math.ceil(((i + 1) / totalPieces) * 100);
      proxy.$showLoading({ tip: `文件下载请求中...(${percent}%)` });
      arr = [...arr, data];
    }
    const fileBlob = new Blob(arr, { type: "application/octet-stream;charset=utf-8" });
    saveAs(fileBlob, rowClickObj.value.AI_Name);
    proxy.$hideLoading();
  } else {
    proxy.$message.warning("请选择要下载的文件!");
  }
};
// 删除
const del = () => {
  if (tableSetting.selectData.length > 0) {
    proxy.$messageBox
      .confirm("确定删除该数据？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
      .then(() => {
        proxy.$vueAxios
          .post(
            "MasterBaseAllInfos/Delete",
            tableSetting.selectData.map((v: any) => v.AI_ID)
          )
          .then((res: any) => {
            if (res.Mark) {
              // dynamicStore.fulltextData.splice(
              //   dynamicStore.fulltextData.findIndex((item: any) => item.AI_ID === rowClickObj.value.AI_ID),
              //   1
              // );
              dynamicStore.fulltextData = dynamicStore.fulltextData.filter(
                (v: any) => !tableSetting.selectData.some((j: any) => j.AI_ID === v.AI_ID)
              );
              proxy.$message.success("删除成功");
            } else {
              proxy.$message.error("删除失败");
            }
          });
      });
  } else {
    proxy.$message.warning("请选择要删除的文件!");
  }
};
// 更新预览窗口状态
const updataVisible = (value: boolean) => {
  fulltextConfig.visible = value;
};
// 按钮点击事件
const onClickVerb = (type: string) => {
  switch (type) {
    case "挂接全文":
      upload();
      break;
    case "下载全文":
      download();
      break;
    case "删除全文":
      del();
      break;
    case "全文OCR":
      OCR();
      break;
    case "权限管理":
      AuthManage();
      break;
    default:
      break;
  }
};
// 全文ocr
const OCR = async () => {
  singalrModal.visible = true;
  if (!singalrModal.AllNetworkStatus) {
    singalrModal.AllNetworkStatus = true;
    singalrModal.circulatingIndex = 0;
    singalrModal.percent = 0;
  }
  for (let i = singalrModal.circulatingIndex; i < tableSetting.selectData.length; i++) {
    singalrModal.circulatingIndex = i;
    const item = tableSetting.selectData[i];
    if (singalrModal.networkStatus && singalrModal.AllNetworkStatus) {
      await proxy.$vueAxios
        .post(
          "MasterBaseSearchOCR/ExecuteContentPage",
          { idList: [item.AI_ID], clientUser: proxy.signalr.connectionId },
          { noLoading: true }
        )
        .then((res: any) => {
          dynamicStore.fulltextData.filter((v: any) => v.AI_ID === item.AI_ID)[0].AI_IsOCR = true;
        });
      singalrModal.percent = Math.round(((singalrModal.circulatingIndex + 1) / tableSetting.selectData.length) * 100);
    } else {
      return;
    }
  }
};
// singalr
const signalrEvent = () => {
  proxy.signalr.off("SendExecuteContentPage");
  proxy.signalr.on("SendExecuteContentPage", (res: any) => {
    singalrModal.text = res;
    if (res.trim().startsWith("start")) {
      // 传输开始
      singalrModal.text = `正在解析第${singalrModal.circulatingIndex + 1}条...`;
    }
    if (res.trim().startsWith("stop")) {
      // 传输结束
      singalrModal.text = `第${singalrModal.circulatingIndex + 1}条已解析完成...`;
      if (singalrModal.circulatingIndex + 1 === tableSetting.selectData.length) {
        singalrModal.circulatingIndex = 0;
        singalrModal.percent = 0;
        singalrModal.visible = false;
        singalrModal.discontinueStatus = false;
        singalrModal.networkStatus = true;
        singalrModal.discontinueFont = "中止";
        singalrModal.AllNetworkStatus = false;
      }
    }
  });
};
// 点击弹出权限管理页面
const AuthManage = () => {
  AuthConfig.title = "权限管理";
  AuthConfig.type = "fullText";
  AuthConfig.visible = true;
};
// 右键事件
const menuClick = async ({ menu, row }: any) => {
  if (tableSetting.selectData.length === 0) {
    proxy.$message.warning("请选中数据!");
    return;
  }
  if (menu.code === "allInfo") {
    // appStore.LoadingConfig.contentLoading = true;
    tableSetting.loading = true;
    for (let i = 0; i < tableSetting.selectData.length; i++) {
      const item = tableSetting.selectData[i];
      const id = proxy.$global.createID();
      await proxy.$vueAxios
        .post(
          "MasterBaseBorrow/Add",
          {
            id: id,
            fM_ID: item.FM_ID,
            fmT_ID: item.FMT_ID,
            status: fatherObj.value.Status,
            record_ID: item.Record_ID,
            stdaList: [{ id: proxy.$global.createID(), stD_ID: id, aI_ID: item.AI_ID }]
          },
          { noLoading: true }
        )
        .then((res: any) => {
          if (res.Mark) {
            proxy.$vueAxios.get("MasterBaseBorrow/Get", {}, { noLoading: true }).then((res: any) => {
              if (res.Mark) {
                userStore.setFileCount(res.Count);
              }
            });
          }
        });
    }
    tableSetting.loading = false;
  }
};
// 中止请求
const cease = () => {
  singalrModal.discontinueStatus = !singalrModal.discontinueStatus;
  singalrModal.networkStatus = !singalrModal.networkStatus;
  if (singalrModal.discontinueStatus) {
    singalrModal.discontinueFont = "恢复";
  } else {
    singalrModal.discontinueFont = "中止";
  }
  OCR();
};
// 取消请求
const cancel = () => {
  singalrModal.circulatingIndex = 0;
  singalrModal.percent = 0;
  singalrModal.visible = false;
  singalrModal.discontinueStatus = false;
  singalrModal.networkStatus = true;
  singalrModal.discontinueFont = "中止";
  singalrModal.AllNetworkStatus = false;
};
// 按钮状态
const toggleDisabled = (val: any) => {
  console.log(val);
  if (["下载全文", "删除全文", "全文OCR", "权限管理"].includes(val.alias)) {
    if (tableSetting.selectData.length <= 0) {
      return (val.disabled = true);
    }
  }
};
watch(
  () => dynamicStore.fulltextData,
  (newVal, oldVal) => {
    console.log(newVal);

    vxeTable.value.reloadData(newVal);
  },
  {
    deep: true
  }
);
onMounted(() => {
  signalrEvent();
});
defineExpose({ getData });
</script>

<style scoped lang="scss"></style>
